package com.music.activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.music.R;
import com.music.utilbean.MediaUtils;
import com.music.utilbean.Mp3Info;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;

public class PlayActivityMusic extends MusicBaseActivity implements OnClickListener, OnSeekBarChangeListener {
	private TextView title, begin_time, end_time;
	private ImageView img_play, img_back, img_go, menu, img_lyric, img_love;
	private SeekBar            seekBar;
	private ArrayList<Mp3Info> mp3Infos;
	private static final int UPDATE_TIME = 0x1;
	private LrcView mLrcView;
	private int     mDuration;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.play);
		title = (TextView) findViewById(R.id.title);
		begin_time = (TextView) findViewById(R.id.begin_time);
		end_time = (TextView) findViewById(R.id.end_time);
		img_play = (ImageView) findViewById(R.id.begin);
		img_back = (ImageView) findViewById(R.id.back);
		img_go = (ImageView) findViewById(R.id.go);
		menu = (ImageView) findViewById(R.id.menu);
		img_lyric = (ImageView) findViewById(R.id.img_lyric);
		seekBar = (SeekBar) findViewById(R.id.skbProgress);
		img_love = (ImageView) findViewById(R.id.love_music);
		img_play.setOnClickListener(this);
		img_back.setOnClickListener(this);
		img_go.setOnClickListener(this);
		menu.setOnClickListener(this);
		img_love.setOnClickListener(this);
		mp3Infos = MediaUtils.getMp3Infos(this);
		myHandler = new MyHandler(this);
		seekBar.setOnSeekBarChangeListener(this);//进度条拖拽
		mLrcView = (LrcView) findViewById(R.id.lrcShowView);

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		bindplayService();

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unbindplayService();
	}

	private static MyHandler myHandler;

	static class MyHandler extends Handler {
		private PlayActivityMusic playActivity;

		public MyHandler(PlayActivityMusic playActivity) {
			this.playActivity = playActivity;
		}

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			if (playActivity != null) {
				switch (msg.what) {
					case UPDATE_TIME:
						playActivity.begin_time.setText(MediaUtils.formatTime((long) msg.arg1));

						break;

					default:
						break;
				}
			}
		}
	}

	@Override
	public void publish(int progress) {
		//实时发生变化的变量
		Message msg = myHandler.obtainMessage(UPDATE_TIME);
		msg.arg1 = progress;
		myHandler.sendMessage(msg);
		seekBar.setProgress(progress);

	}

	@Override
	public void change(int position) {//状态性变量改变
		Mp3Info mp3Info = mp3Infos.get(position);
		setLrcView();
		title.setText(mp3Info.getTitle());
		end_time.setText(MediaUtils.formatTime(mp3Info.getDuration()));
		if (query(playService.getCurrentPosition())) {
			img_love.setImageResource(R.drawable.keep);//设置如果在收藏db查询的当前播放歌曲的信息返回true则把图标设置为红心
		} else {
			img_love.setImageResource(R.drawable.nokeep);
		}
		Bitmap bm = MediaUtils.getArtwork(this, mp3Info.getId(), mp3Info.getAlbumId(), true, false);
		img_lyric.setImageBitmap(bm);
		seekBar.setProgress(0);
		seekBar.setMax((int) mp3Info.getDuration());
		if (playService.isplaying()) {
			img_play.setImageResource(R.drawable.pause);
		} else {
			img_play.setImageResource(R.drawable.begin);
		}
		switch (playService.getPlay_mode()) {
			case PlayService.ORDER_PLAY:
				menu.setImageResource(R.drawable.menu);
				menu.setTag(PlayService.ORDER_PLAY);
				break;
			case PlayService.RANDOM_PLAY:
				menu.setImageResource(R.drawable.shuffl);
				menu.setTag(PlayService.RANDOM_PLAY);
				break;
			case PlayService.SINGLE_PLAY:
				menu.setImageResource(R.drawable.repeat);
				menu.setTag(PlayService.SINGLE_PLAY);
			default:
				break;
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
			case R.id.begin:
				if (playService.isplaying()) {
					img_play.setImageResource(R.drawable.begin);
					playService.pause();
				} else {
					if (playService.ispause()) {
						img_play.setImageResource(R.drawable.pause);
						playService.start();
					} else {
						playService.play(sp.getInt("currentposition", playService.getCurrentPosition()));
					}

				}
				break;
			case R.id.go:
				playService.next();
				break;
			case R.id.back:
				playService.prev();
				break;
			case R.id.menu:
				int mode = (Integer) menu.getTag();
				switch (mode) {
					case PlayService.ORDER_PLAY:
						menu.setImageResource(R.drawable.shuffl);
						menu.setTag(PlayService.RANDOM_PLAY);
						playService.setPlay_mode(PlayService.RANDOM_PLAY);
						Toast.makeText(this, "随机播放已开启", Toast.LENGTH_SHORT).show();
						break;
					case PlayService.RANDOM_PLAY:
						menu.setImageResource(R.drawable.repeat);
						menu.setTag(PlayService.SINGLE_PLAY);
						playService.setPlay_mode(PlayService.SINGLE_PLAY);
						Toast.makeText(this, "单曲循环已开启", Toast.LENGTH_SHORT).show();
						break;
					case PlayService.SINGLE_PLAY:
						menu.setImageResource(R.drawable.menu);
						menu.setTag(PlayService.ORDER_PLAY);
						playService.setPlay_mode(PlayService.ORDER_PLAY);
						Toast.makeText(this, "顺序播放已开启", Toast.LENGTH_SHORT).show();
						break;

				}
				break;
			case R.id.love_music:
				if (query(playService.getCurrentPosition())) {
					delete(playService.getCurrentPosition());
					img_love.setImageResource(R.drawable.nokeep);
					Toast.makeText(this, "取消收藏", Toast.LENGTH_SHORT).show();
				} else {
					add(playService.getCurrentPosition(), mp3Infos.get(playService.getCurrentPosition()).getTitle());
					img_love.setImageResource(R.drawable.keep);
					Toast.makeText(this, "添加收藏", Toast.LENGTH_SHORT).show();
				}

			default:
				break;
		}
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromuser) {
		if (fromuser) {
			playService.pause();
			playService.seekTo(progress);
			playService.start();


		}

	}

	@Override
	public void onStartTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStopTrackingTouch(SeekBar arg0) {
		// TODO Auto-generated method stub

	}

	///////////////////////////////////////////////////////////////////
	//收藏关联sqlitedatabase
	private void add(int mp3id, String mp3name) {

		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("mp3infoID", mp3id + "");
		values.put("title", mp3name);
		db.insert("mymusic", null, values);

	}

	private void delete(int mp3id) {
		SQLiteDatabase db = helper.getWritableDatabase();
		db.delete("mymusic", "mp3infoID=?", new String[]{mp3id + ""});
		db.close();
	}

	private boolean query(int mp3id) {

		SQLiteDatabase db = helper.getWritableDatabase();
		Cursor cursor = db.rawQuery("select * from mymusic where mp3infoID=?", new String[]{mp3id + ""});
		boolean result = cursor.moveToNext();
		cursor.close();
		db.close();
		return result;
	}
	//////////////////////////////////////歌词部分

	private void setLrcView() {
		try {
			String path = mp3Infos.get(playService.getCurrentPosition()).getUrl().replace(".mp3", ".lrc");
			Log.i("path", "歌词文件路径:" + path);
			File file = new File(path);
			//创建一个文件输入流对象
			InputStream is = new FileInputStream(file);
			mLrcView.setLrcList(is); // 传入歌词文件流
			showLrc();
			//isInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
			Log.i("setLrcViewException", "异常");
		}
	}

	/**
	 * 没100毫秒传入歌曲播放进度
	 */
	private void showLrc() {
		mLrcView.postDelayed(new Runnable() {
			@Override
			public void run() {
				mDuration = playService.getDuration();
				int currentPositions = playService.getcurrentpositions();
				mLrcView.setIndex(currentPositions, mDuration);
				mLrcView.postDelayed(this, 100);
			}
		}, 100);
	}
}
